package com.rfid.afd.presenter;

import android.os.Handler;

import com.rfid.afd.activity.view.ILoginView;
import com.rfid.config.ConfigManager;
import com.rfid.config.Constant;
import com.rfid.db.bean.User;
import com.rfid.rls_psw.App;
import com.rfid.util.DBManager;
import com.rfid.util.FileUtil;
import com.rfid.util.NetUtil;
import com.rfid.util.UserManager;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class LoginPresenter extends BasePresenter<ILoginView>{

    private ILoginView mILoginView;
    private Executor mExecutor = Executors.newSingleThreadExecutor();
    private Handler mHandler;
    public LoginPresenter(ILoginView view) {
        mILoginView = view;
        mHandler = new Handler();
    }

    public void login(String userName,String password,boolean online,String library) {
        List<User> users = DBManager.queryUsers();
        if(users.size() == 0) {
            User user = new User(null,"admin","1","","");
            DBManager.insertUser(user);
            users.add(user);
        }
        for(User user : users) {
            if(user.getName().equals(userName) && user.getPassword().equals(password)) {
                UserManager.getInstance().setLoginUser(user);
                mILoginView.onLoginSuccess(online);
                return;
            }
        }
        mILoginView.onLoginFail("登录失败，请检查账号密码");
    }

    public void checkOrdownloadDBFile() {
        File file = new File(Constant.DB_PATH);
        if(file.exists()) {
            mILoginView.onDBPreparedSuccess();
            return;
        }
        mILoginView.showLoading();
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String path = "/sdcard/rfid.db.cache";
                    NetUtil.downloadFile(ConfigManager.getInstance().getConfig().getBaseUrl() + "/download/download?filename=rfid.db", path);
                    FileUtil.rm("/sdcard/rfid.db-wal");
                    FileUtil.rm("/sdcard/rfid.db-shm");
                    FileUtil.mv("/sdcard/rfid.db.cache", Constant.DB_PATH);
                    if(mILoginView != null)
                        mILoginView.onDBPreparedSuccess();
                } catch (Exception e) {
                    e.printStackTrace();
                    if(mILoginView != null)
                        mILoginView.onDBPreparedFail();
                } finally {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if(mILoginView != null)
                                mILoginView.stopLoading();
                        }
                    });
                }
            }
        });
    }
}
